package com.jsnkj.basic.advertisement

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import com.jsnkj.basic.bean.AdSettingBaseEntity
import com.jsnkj.basic.bean.AdSettingListBean
import com.jsnkj.basic.config.RewardsConfig
import com.jsnkj.basic.config.SpConfig
import com.jsnkj.basic.util.SharePreferencesUtil
import com.hzhj.openads.HJAdsSdkBanner
import com.hzhj.openads.HJAdsSdkInterstitial
import com.hzhj.openads.HJAdsSdkReward
import com.hzhj.openads.HJAdsSdkSplash
import com.hzhj.openads.HjAdsSdkNativeAd
import com.hzhj.openads.constant.HJConstants
import com.hzhj.openads.domain.HJAdError
import com.hzhj.openads.domain.HJNativeAdData
import com.hzhj.openads.listener.HJOnAdsNativeAdLoadListener
import com.hzhj.openads.listener.HJOnAdsSdkBannerListener
import com.hzhj.openads.listener.HJOnAdsSdkInterstitialListener
import com.hzhj.openads.listener.HJOnAdsSdkRewardListener
import com.hzhj.openads.listener.HJOnAdsSdkSplashListener
import com.hzhj.openads.req.HJBannerAdRequest
import com.hzhj.openads.req.HJInterstitialAdRequest
import com.hzhj.openads.req.HJNativeAdRequest
import com.hzhj.openads.req.HJRewardAdRequest
import com.hzhj.openads.req.HJSplashAdRequest
import com.kwad.sdk.api.KsContentPage
import com.kwad.sdk.api.KsScene
import com.windmill.sdk.WMConstants


/**
 * 广告管理工具
 */
object AdvertisementManager {

    private const val TAG = "启动广告"

    var isInit = false

    fun getAdSettingBaseEntity(): AdSettingBaseEntity {
        return SharePreferencesUtil.getInstance().getAdSettingEntity()
    }


    /**
     * 根据标识得到的 广告信息
     */
    fun getAdSettingListBean(identification: String): AdSettingListBean? {
        val configBean = getAdSettingBaseEntity()
        //隐藏广告，测试时使用 2024年6月5日10:56:33
        if (!configBean.list.isNullOrEmpty()) {
            for ((_, bean) in configBean.list!!.withIndex()) {
                if (identification == bean.position) {
                    return bean
                }
            }
        }
        return null
    }


    /**
     * 判断广告是否正常使用
     */
    fun getAdShowLoad(identification: String): Boolean {
        if (!isInit) {
            com.jsnkj.basic.util.LogUtils.e("广告SDK 未初始化---- ")
//            return false
        }

        var isShowAd = SharePreferencesUtil.getInstance().getUserBean()?.user?.is_show_ad
        if (null != isShowAd && 0 == isShowAd) {
            return false
        }

        if (null == getAdSettingListBean(identification)) {
            com.jsnkj.basic.util.LogUtils.e("广告SDK getAdShowLoad   数据为空---- ")
            return false
        }

        if ("enabled" != getAdSettingListBean(identification)!!.status) {
            com.jsnkj.basic.util.LogUtils.e("广告SDK getAdShowLoad   开关为关闭---- ")
            return false
        }
        return true
    }


    /**
     * 判断当前时间时候满足间隔时间
     *
     * @return
     */
    fun getShowTimeOpenAd(intervalTime: Long, key: String): Boolean {
        val currentTime = System.currentTimeMillis() / 1000
        //上次显示广告的时间
        val lastTime = SharePreferencesUtil.getInstance().getLong(key, 0L)

        val resultTime = currentTime - lastTime >= intervalTime
        com.jsnkj.basic.util.LogUtils.e("key == $key  得到当前时间：$currentTime 上次插屏的时间：$lastTime 结果是：$resultTime")

        if (resultTime) {
            //保存显示广告的时间
            SharePreferencesUtil.getInstance().putLong(key, currentTime)
            return true
        }
        return false
    }


    /**
     * 开屏广告 判断当前时间时候满足间隔时间
     *
     * @return
     */
    fun getShowOpenAd(intervalTime: Long): Boolean {
        return getShowTimeOpenAd(intervalTime, SpConfig.STREAM_OPEN_AD_TIME)
    }


    /**
     * 广告SDK初始化
     */
    fun initAdvertisement(appContext: Context, initListener: Object) {
        if (getAdSettingBaseEntity().media_id.isNullOrEmpty()) {
           // initListener.onFail("initAdvertisement  数据为空 初始化失败")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.initAdEvent("load")

//        val config = com.tb.mob.config.TbInitConfig.Builder()
//            .appId(getAdSettingBaseEntity().media_id)
//            .build()
//        com.tb.mob.TbManager.init(appContext, config, initListener)
    }

    fun initHjAdvertisement(appContext: Context) {
        if (getAdSettingBaseEntity().media_id.isNullOrEmpty()) {
            // initListener.onFail("initAdvertisement  数据为空 初始化失败")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.initAdEvent("load")

    }



    /**
     * 加载开屏广告
     */
    fun loadSplash(
        activity: Activity, viewGroup: ViewGroup,
        splashLoadLister: Object
    ) {


        if (!getAdShowLoad(RewardsConfig.adOpenscene)) {
          //  splashLoadLister.onFail("广告加载失败")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.splashAdEvent("load")

//        val config = com.tb.mob.config.TbSplashConfig.Builder()
//            .codeId(getAdSettingListBean(RewardsConfig.adOpenscene)!!.value) //平台申请的代码位id
//            .container(viewGroup) //承载视图的容器。可⾃定义⾼度⽐例,但不能低于0.75
//            .build()
//        com.tb.mob.TbManager.loadSplash(config, activity, splashLoadLister)
    }


    /**
     *  根据时间间隔加载插屏广告
     */
    fun showLoadInteraction(activity: Activity) {
        val getad = getAdShowLoad(RewardsConfig.adInterrupt)
        val gettime = getShowTimeOpenAd(SpConfig.OPEN_MAIN_AD_TIME, SpConfig.MAIN_OPEN_AD_TIME)
        val getBool = SharePreferencesUtil.getInstance().getBoolean(SpConfig.APP_LOCK_SCREEN, true)

        com.jsnkj.basic.util.LogUtils.e("是否弹出插屏 getad = $getad " + " gettime = $gettime" + " getBool = $getBool")

        //开启插屏广告
        if (getad && gettime && getBool) {
            loadInteraction(
                activity, SharePreferencesUtil.getInstance().getInt("app_screenWidth", 0)
            )
        }
    }


    /**
     *  根据时间间隔加载插屏广告
     */
    fun showLoadInteraction(activity: Activity, intervalTime: Long) {
        //开启插屏广告
        if (getAdShowLoad(RewardsConfig.adInterrupt)
            && getShowTimeOpenAd(intervalTime, SpConfig.MAIN_OPEN_AD_TIME)
        ) {
            loadInteraction(
                activity, SharePreferencesUtil.getInstance().getInt("app_screenWidth", 0)
            )
        }
    }


    /**
     * 加载插屏广告
     */
    fun loadInteraction(activity: Activity, viewWidth: Int) {
        SharePreferencesUtil.getInstance()
            .putBoolean(SpConfig.APP_LOCK_SCREEN, false)
        val options:HashMap<String,Any> = hashMapOf(
            "key" to "插屏广告"
        )
        loadHjInterstitialAds(activity,options,object :HJOnAdsSdkInterstitialListener{
            override fun onInterstitialAdLoadSuccess(p0: String?) {
                if (interstitialAd != null && interstitialAd!!.isReady) {
                    //广告播放
                    val option: HashMap<*, *> = HashMap<Any?, Any?>()
                    interstitialAd!!.show(option)
                }
            }

            override fun onInterstitialAdPlayStart() {
               com.jsnkj.basic.util.LogUtils.i("onInterstitialAdPlayStart");
            }

            override fun onInterstitialAdPlayEnd() {
                com.jsnkj.basic.util.LogUtils.i("onInterstitialAdPlayEnd");
            }

            override fun onInterstitialAdClicked() {
                com.jsnkj.basic.util.LogUtils.i("onInterstitialAdClicked");
            }

            override fun onInterstitialAdClosed() {
                com.jsnkj.basic.util.LogUtils.i("onInterstitialAdClosed");
            }

            override fun onInterstitialAdLoadError(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("onInterstitialAdLoadError="+p1+" "+p0!!.msg)
            }

            override fun onInterstitialAdPlayError(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("onInterstitialAdPlayError="+p1+" "+p0!!.msg)
            }

        })
    }


    /**
     * 加载插屏广告
     */
    fun loadInteraction(
        activity: Activity,
        viewWidth: Int,
        interactionLoadLister: Object
    ) {

        if (!getAdShowLoad(RewardsConfig.adInterrupt)) {
            return
        }
//        val config = com.tb.mob.config.TbInteractionConfig.Builder()
//            .codeId(getAdSettingListBean(RewardsConfig.adInterrupt)!!.value) //平台申请的代码位id
//            .viewWidth(viewWidth) //期望模板view的width（height自适应），默认值450（单位dp）
//            .build()
//        com.tb.mob.TbManager.loadInteraction(config, activity, interactionLoadLister)
    }


    /**
     * 加载信息流
     */
    fun loadFeed(
        activity: Activity, width: Int, height: Int,
        feedLoadListener: Object
    ) {

        if (!getAdShowLoad(RewardsConfig.adStream)) {
            com.jsnkj.basic.util.LogUtils.e("信息流加载失败")
            return
        }

        if (!getShowTimeOpenAd(SpConfig.AD_TIME, SpConfig.BANNER_AD_TIME)) {
            com.jsnkj.basic.util.LogUtils.e("广告SDK getAdShowLoad   时间间隔不够---- ")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.flowAdEvent("load")

//        LogUtils.e("信息流广告加载：" + getAdSettingListBean(RewardsConfig.adStream)!!.value)
//        val config = com.tb.mob.config.TbFeedConfig.Builder()
//            .codeId(getAdSettingListBean(RewardsConfig.adStream)!!.value) //平台申请的代码位id
//            .viewWidth(width) //期望模板view的width，默认值350（单位dp）
//            .viewHigh(height) //期望模板view的height，默认值0（自适应，单位dp）
//            .build()
//        com.tb.mob.TbManager.loadFeed(config, activity, feedLoadListener)
    }


    /**
     * 加载 激励视频
     */
    fun loadRewardVideo(
        activity: Activity,
        extraData: String,
        orientation: Object,
        rewardVideoLoadListener: Object
    ) {
        if (!getAdShowLoad(RewardsConfig.adStimulate)) {
          //  rewardVideoLoadListener.onFail("激励视频数据获取失败")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.playJlspAdEvent("load")

//        val config = TbRewardVideoConfig.Builder()
//            .codeId(getAdSettingListBean(RewardsConfig.adStimulate)!!.value) //平台申请的代码位id
//            .userId(SharePreferencesUtil.getInstance().getUid()) //必填参数，用户ID或者设备唯一标识（服务器回调时也需要）
//            .callExtraData(extraData) //服务器回调额外信息（可不填）
//            .orientation(orientation) //必填参数，期望视频的播放方向：VIDEO_HORIZONTAL 或 VIDEO_VERTICAL
//            .build()
//        com.tb.mob.TbManager.loadRewardVideo(config, activity, rewardVideoLoadListener)
    }


    /**
     * 加载 Banner视频
     */
    fun loadBanner(
        activity: Activity,
        width: Int = 350, viewGroup: ViewGroup,
        bannerLoadListener: Object
    ) {
        if (!getAdShowLoad(RewardsConfig.adBanner)) {
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.bannerAdEvent("load")

//        val config = TbBannerConfig.Builder()
//            .codeId(getAdSettingListBean(RewardsConfig.adBanner)!!.value) //平台申请的代码位id
////            .viewWidth(width) //期望模板view的width（height自适应），默认值350（单位dp）
////            .viewHight((width / 6.4f).toInt())
//            .container(viewGroup) //承载视图的容器
//            .build()
//
//        com.tb.mob.TbManager.loadBanner(config, activity, bannerLoadListener);

    }


    /**
     * 加载短视频信息流
     */
    fun loadDrawFeed(
        activity: Activity,
        fragmentID: Int,
        drawfeed: Object
    ) {
        if (!getAdShowLoad(RewardsConfig.adShorts)) {
//            LogUtils.e("加载短视频信息流 失败")
           // drawfeed.onFail("加载短视频信息流 失败")
            return
        }
        com.jsnkj.basic.burialpoint.BurialPointUtil.shortVideoAdEvent("load")

//        LogUtils.e("加载短视频信息流 " + getAdSettingListBean(RewardsConfig.adShorts)!!.value)
        //显示短视频
//        val config = TbVideoConfig.Builder()
//            .codeId(getAdSettingListBean(RewardsConfig.adShorts)!!.value) //平台申请的代码位id
//            .containerIdRes(fragmentID)
//            .reward_switch(true)
//            .build()
//
//        com.tb.mob.TbVideoManager.replaceFrameLayout4Video(activity, config, drawfeed)

    }

    //最新灰鲸广告部分

    /**
     * 加载开屏广告-灰鲸网络
     */
    private var mSplashAd : HJAdsSdkSplash ? = null
    fun loadHjSplash(
        activity: Activity, viewGroup: ViewGroup,
        splashLoadLister: HJOnAdsSdkSplashListener
    ) {

        if (!getAdShowLoad(RewardsConfig.adOpenscene)) {
            splashLoadLister.onSplashAdFailToLoad(HJAdError.parseErr(HJAdError.ERROR_AD_HTTP),"开屏广告加载失败")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.splashAdEvent("load")
        val adId = getAdSettingListBean(RewardsConfig.adOpenscene)!!.value;
        com.jsnkj.basic.util.LogUtils.i("启动广告Id="+adId)

        if(mSplashAd == null){
            val hjSplashAdRequest = HJSplashAdRequest(adId, null, null)
            mSplashAd = HJAdsSdkSplash(activity, hjSplashAdRequest, splashLoadLister)
        }
        mSplashAd?.loadAndShow(viewGroup)
    }

    private var adSdkReward: HJAdsSdkReward? = null
    /**
     * 灰鲸激励广告
     */
    fun loadHjRewardAds(activity: Activity,rewardListener: HJOnAdsSdkRewardListener) {
        if (!getAdShowLoad(RewardsConfig.adStimulate)) {
            rewardListener.onVideoAdLoadError(HJAdError.parseErr(HJAdError.ERROR_AD_HTTP),"激励广告加载失败")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.splashAdEvent("load")
        val adId = getAdSettingListBean(RewardsConfig.adStimulate)!!.value;
        com.jsnkj.basic.util.LogUtils.e("激励广告Id="+adId)

        if(adSdkReward == null){
            //用于激励回调
            var userId = SharePreferencesUtil.getInstance().getUid()
            val hjRewardAdRequest = HJRewardAdRequest(adId, userId, null)
            adSdkReward = HJAdsSdkReward(
                activity,
                activity,
                hjRewardAdRequest,
                rewardListener
            )
        }
        adSdkReward?.loadAd();

    }

    /**
     * 播放激励广告
     */
    fun showHJRewardAds(option:HashMap<String,String>){
        if (adSdkReward!!.isReady) {
            adSdkReward!!.show(option)
        }
    }

    /**
     * 加载banner广告
     */
    private var hjAdsSdkBanner: HJAdsSdkBanner? = null

    fun loadHjBannerAds(activity: Activity, hjOnAdsSdkBannerListener: HJOnAdsSdkBannerListener) {
        if (!getAdShowLoad(RewardsConfig.adBanner)) {
            hjOnAdsSdkBannerListener.onAdLoadError(HJAdError.parseErr(HJAdError.ERROR_AD_HTTP),"Banner广告加载失败")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.bannerAdEvent("load")
        val adId = getAdSettingListBean(RewardsConfig.adBanner)!!.value;
        com.jsnkj.basic.util.LogUtils.e("Banner广告Id="+adId)
        val hjBannerAdRequest = HJBannerAdRequest(adId, null, null)
        if(hjAdsSdkBanner == null){
            hjAdsSdkBanner = HJAdsSdkBanner(activity, hjOnAdsSdkBannerListener)
        }
        hjAdsSdkBanner!!.loadAd(hjBannerAdRequest)
    }

    /**
     * 播放Banner广告
     */
    fun showHJBannerAds(viewGroup: ViewGroup){
        if (hjAdsSdkBanner!!.isReady) {
            hjAdsSdkBanner!!.showAd(viewGroup)
        }
    }

    /**
     * 加载信息流广告
     */
    private var nativeAd: HjAdsSdkNativeAd? = null

    fun loadHjNativeAds(activity: Activity, feedAdsListener: com.jsnkj.basic.adlistener.FeedAdsListener, adWidth:Int) {
        if (!getAdShowLoad(RewardsConfig.adStream)) {
            feedAdsListener.onFeedLoadFail("信息流广告加载失败")
            return
        }


        if (!getShowTimeOpenAd(SpConfig.AD_TIME, SpConfig.BANNER_AD_TIME)) {
            com.jsnkj.basic.util.LogUtils.e("广告SDK getAdShowLoad   时间间隔不够---- ")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.flowAdEvent("load")
        val adId = getAdSettingListBean(RewardsConfig.adStream)!!.value;
        com.jsnkj.basic.util.LogUtils.i("信息流广告Id="+adId)

        val options: MutableMap<String, Any> = HashMap()
        options[HJConstants.AD_WIDTH] = adWidth //针对于模版广告有效、单位dp

        options[HJConstants.AD_HEIGHT] = WMConstants.AUTO_SIZE //默认自适应高度、单位dp

        val request = HJNativeAdRequest(adId, null, 1, options)
        if(nativeAd == null){
            nativeAd = HjAdsSdkNativeAd(activity, request)
        }

        val hjOnAdsNativeAdLoadListener = object : HJOnAdsNativeAdLoadListener {
            override fun onError(error: HJAdError, placementId: String) {
                feedAdsListener.onFeedLoadFail(error.msg+"信息流广告加载失败")
            }

            override fun onFeedAdLoad(placementId: String) {
                val unifiedADData: List<HJNativeAdData> = nativeAd!!.nativeAdDataList;
                if (unifiedADData != null && unifiedADData.size > 0) {
                    feedAdsListener.onFeedLoadSuccess(unifiedADData);
                }
            }
        }
        nativeAd?.loadAd(hjOnAdsNativeAdLoadListener);

    }

    /**
     * 灰鲸短视频广告
     */

    private var mKSPage: KsContentPage? = null
    fun loadHjVideoAds(fragmentManager: FragmentManager,containerViewId: Int){
        if (!getAdShowLoad(RewardsConfig.adShorts)) {
            com.jsnkj.basic.util.LogUtils.e("信息流广告加载失败")
            return
        }

        if (!getShowTimeOpenAd(SpConfig.AD_TIME, SpConfig.BANNER_AD_TIME)) {
            com.jsnkj.basic.util.LogUtils.e("广告SDK getAdShowLoad   时间间隔不够---- ")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.flowAdEvent("load")
        val adId = getAdSettingListBean(RewardsConfig.adShorts)!!.value as String;
        com.jsnkj.basic.util.LogUtils.i("短视频广告Id="+adId)
        var videoAdId:Long = 0;
        if(adId!=null){
            videoAdId = adId.toLongOrNull() as Long;
        }
        if(mKSPage == null){
            val adScene: KsScene = com.jsnkj.basic.util.KSSdkInitUtil.createKSSceneBuilder(videoAdId).build()
            mKSPage = com.jsnkj.basic.util.KSSdkInitUtil.getLoadManager().loadContentPage(adScene)
        }
        var videoResult:Int = fragmentManager.beginTransaction()
            .replace(containerViewId, mKSPage!!.fragment)
            .commitAllowingStateLoss()
        com.jsnkj.basic.util.LogUtils.i("videoResult=="+videoResult)
    }

    private var interstitialAd: HJAdsSdkInterstitial? = null
    fun loadHjInterstitialAds(activity: Activity,options:HashMap<String,Any>,listener:HJOnAdsSdkInterstitialListener){
        if (!getAdShowLoad(RewardsConfig.adInterrupt)) {
            com.jsnkj.basic.util.LogUtils.e("插屏广告加载失败")
            return
        }


        if (!getShowTimeOpenAd(SpConfig.AD_TIME, SpConfig.BANNER_AD_TIME)) {
            com.jsnkj.basic.util.LogUtils.e("广告SDK getAdShowLoad   时间间隔不够---- ")
            return
        }

        com.jsnkj.basic.burialpoint.BurialPointUtil.cpAdEvent("load")
        val adId = getAdSettingListBean(RewardsConfig.adInterrupt)!!.value as String;
        com.jsnkj.basic.util.LogUtils.i("插屏广告Id="+adId)

        val request = HJInterstitialAdRequest(adId, null, options)
        if(interstitialAd == null){
            interstitialAd = HJAdsSdkInterstitial(activity, request, listener)
        }
        interstitialAd!!.loadAd();
    }


}